<template>
  <view class="detail-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 商品图片 -->
    <image class="product-image" :src="product.image" mode="aspectFit"></image>
    
    <!-- 商品价格列表 -->
    <view class="price-list">
      <view 
        class="price-item" 
        v-for="(spec, index) in specifications" 
        :key="index"
        :class="{ active: selectedSpec && selectedSpec.size === spec.size }"
        @tap="selectedSpec = spec"
      >
        <text>{{ spec.name }}</text>
        <text class="price">{{ spec.price }}元/{{ product.unit }}</text>
      </view>
    </view>

    <!-- 服务描述 -->
    <view class="service-desc" v-if="product.description">
      <view class="desc-title">服务描述</view>
      <view class="desc-content">{{ product.description }}</view>
    </view>

    <!-- 订购须知 -->
    <view class="order-notice">
      <view class="desc-title">订购须知</view>
      <view class="desc-content">
        <view class="notice-item">【订购须知】</view>
        <view class="notice-item">1、SPA物料包、中式推拿包为一次性贴肤使用用品，售出后不退不换；</view>
        <view class="notice-item">2、下单后，不修改订单内容（包括修改衣服尺码，更改地址/收件人/电话等）请仔细核对订单内容后下单；按订单系统定位地址发货，因订单定位地址、电话、姓名(包括非真实姓名)等错误/不详造成的错发、无法准运派送的，收件人自行联系物流公司提供准确地址或告知物流拒收，快递退回后扣除及快递时所产生的运费后退；</view>
        <view class="notice-item">3、已发货订单，如要修改地址请自行与物流公司联系，因此所产生的其他费用自行承担；如因修改地址造成快递丢失、无法送达等情况责任自负；修改地址是否成功以物流公司为准；</view>
        <view class="notice-item">4、已发货订单，要求拦截退回的，快递退回后以实际产生运费为准扣除运费退余款；</view>
        <view class="notice-item">5、因多次联系不到收件人致使快递放至代收点/驿站或因地无法派送造成丢失责任自付；快递已送达驿站/丰巢/代收点等，长时间未取造成快递物品丢失，责任自负；</view>
        <view class="notice-item">6、自签收之日起7日内可退换，换货/退货/拒收（长时间联系不到收件人视为拒收）在收到退回商品后，均扣除发快递时所产生的运费后退余款。自行递回的快递快递费自理，到付拒收！</view>
      </view>
    </view>

    <!-- 发货说明 -->
    <view class="shipping-notice">
      <view class="desc-title">发货说明</view>
      <view class="desc-content">
        <view class="notice-item">1、无加急，尽快安排发出</view>
        <view class="notice-item">2、工作日16:00前订单当天发出，16:00后订单次日发出</view>
        <view class="notice-item">3、不接受指定快递，平台统一安排河北云仓发出，运输天数以物流实际运输周期为准，平台不做预估，快递信息在发出后次日更新</view>
      </view>
    </view>

    <!-- 图片描述 -->
    <view class="image-desc" v-if="product.otherImage">
      <image :src="product.otherImage" mode="widthFix" class="desc-image"></image>
    </view>

    <!-- 商品说明（尺码表等） -->
    <view class="product-desc" v-if="product.type=='uniform'">
      <view class="desc-title">套装说明：</view>
      <view class="desc-content">
        <view>工服套装：</view>
        <view>1. T恤一件</view>
        <view>2. 背包一个</view>
        <view>3. SPA物料包 25套</view>
      </view>

      <view class="desc-title">注意事项：</view>
      <view class="desc-content">
        <view>【尺码说明】</view>
        <view>1. 工服尺码一经选择，不予更换，请仔细确认尺码。</view>
        <view>2. 工服尺码表如下，请根据自身情况选择合适尺码。</view>
      </view>

      <!-- 尺码表 -->
      <view class="size-table">
        <view class="table-header">
          <text class="cell">尺码</text>
          <text class="cell">胸围</text>
          <text class="cell">衣长</text>
          <text class="cell">肩宽</text>
          <text class="cell">建议身高</text>
          <text class="cell">建议体重</text>
        </view>
        <view class="table-row" v-for="(size, index) in sizeTable" :key="index">
          <text class="cell">{{ size.name }}</text>
          <text class="cell">{{ size.chest }}</text>
          <text class="cell">{{ size.length }}</text>
          <text class="cell">{{ size.shoulder }}</text>
          <text class="cell">{{ size.height }}</text>
          <text class="cell">{{ size.weight }}</text>
        </view>
      </view>

      <view class="desc-title">【发货说明】</view>
      <view class="desc-content">
        <view>1. 工服套装统一发货，不单独邮寄。</view>
        <view>2. 工服套装发货后，不接受退换。</view>
        <view>3. 如遇缺货，将及时与您联系。</view>
      </view>
    </view>
    <!-- 右下角确认按钮 -->
  <view class="confirm-btn" @tap="confirmAddToCart">
    <text>确认</text>
  </view>
  </view>

  
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
  data() {
    return {
      product: {
        id: 0,
        title: '',
        image: '',
        tag: '',
        notice: '',
        price: '',
        unit: '',
        specifications: '',
        type: '',
        description: '',
			  otherImage: '',
      },
      sizeTable: [
        { name: 'S', chest: '47', length: '65', shoulder: '42', height: '155-165', weight: '45-55' },
        { name: 'M', chest: '49', length: '67', shoulder: '44', height: '160-170', weight: '55-65' },
        { name: 'L', chest: '51', length: '69', shoulder: '46', height: '165-175', weight: '65-75' },
        { name: 'XL', chest: '53', length: '71', shoulder: '48', height: '170-180', weight: '75-85' },
        { name: '2XL', chest: '55', length: '73', shoulder: '50', height: '175-185', weight: '85-95' }
      ],
      selectedSpec: null
    }
  },
  computed: {
    specifications() {
      if (!this.product.specifications) return []
      return this.product.specifications.split(',').map(spec => ({
        name: spec + "  "+this.product.title,
        price: this.product.price,
        size: spec
      }))
    }
  },
  onLoad(options) {
    if (options.product) {
      try {
        const productData = JSON.parse(decodeURIComponent(options.product))
        console.log(productData)
        this.product = productData
        // 如果有规格数据，默认选中第一个
        if (this.specifications.length > 0) {
          this.selectedSpec = this.specifications[0]
        }
        uni.setNavigationBarTitle({
          title: productData.title || '商品详情'
        })
      } catch (error) {
        console.error('解析商品数据失败:', error)
        uni.showToast({
          title: '商品数据错误',
          icon: 'none'
        })
      }
    }
  },
  methods: {
    placeOrder() {
      if (!this.selectedSpec) {
        uni.showToast({
          title: '请选择规格',
          icon: 'none'
        })
        return
      }

      uni.navigateTo({
        url: `/pages/technician/supplieOrder?orderItems=${encodeURIComponent(JSON.stringify([{
          ...this.product,
          specification: this.selectedSpec.size,
          specificationName: this.selectedSpec.name,
          quantity: 1
        }]))}`
      })
    },
    confirmAddToCart() {
      // 只有当商品有规格时才检查是否选择了规格
      if (this.product.specifications && this.product.specifications.trim() !== '') {
        if (!this.selectedSpec) {
          uni.showToast({
            title: '请选择规格',
            icon: 'none'
          })
          return
        }
      }

      // 构造购物车商品数据
      const cartItem = {
        id: this.product.id,
        title: this.product.title,
        image: this.product.image,
        price: parseFloat(this.product.price),
        unit: this.product.unit,
        type: this.product.type,
        description: this.product.description,
        otherImage: this.product.otherImage,
        specifications: this.selectedSpec ? this.selectedSpec.size : '',
        specificationName: this.selectedSpec ? this.selectedSpec.name : this.product.title,
        quantity: 1
      }

      // 获取localStorage中的购物车数据
      let cartItems = []
      try {
        const savedCart = localStorage.getItem('supplieCart')
        if (savedCart) {
          cartItems = JSON.parse(savedCart)
        }
      } catch (e) {
        console.error('读取购物车数据失败:', e)
        cartItems = []
      }

      // 检查购物车中是否已存在相同商品
      // 对于有规格的商品，需要同时比较商品ID和规格
      // 对于无规格的商品，只需要比较商品ID
      const existingIndex = cartItems.findIndex(item => {
        if (this.product.specifications && this.product.specifications.trim() !== '') {
          // 有规格的商品：需要ID和规格都相同
          return item.id === cartItem.id && item.specifications === cartItem.specifications
        } else {
          // 无规格的商品：只需要ID相同
          return item.id === cartItem.id
        }
      })

      if (existingIndex !== -1) {
        // 如果商品已存在，增加数量
        cartItems[existingIndex].quantity += 1
        uni.showToast({
          title: '商品数量已更新',
          icon: 'success'
        })
      } else {
        // 如果商品不存在，添加到购物车
        cartItems.push(cartItem)
        uni.showToast({
          title: '已添加到购物车',
          icon: 'success'
        })
      }

      // 保存到localStorage
      try {
        localStorage.setItem('supplieCart', JSON.stringify(cartItems))
      } catch (e) {
        console.error('保存购物车数据失败:', e)
        uni.showToast({
          title: '保存失败',
          icon: 'error'
        })
        return
      }

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
}

.product-image {
  width: 100%;
  height: 750rpx;
  object-fit: contain;
  background-color: #f8f8f8;
}

.price-list {
  background: #FFFFFF;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
    border: 2rpx solid transparent;
    border-radius: 8rpx;
    margin-bottom: 10rpx;

    &.active {
      border-color: #FF0000;
      background: #FFF0F0;
    }

    .price {
      color: #FF0000;
    }
  }
}

.service-desc,
.order-notice,
.shipping-notice,
.logistics-query {
  background: #FFFFFF;
  padding: 20rpx;
  margin-bottom: 20rpx;

  .desc-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .desc-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.8;

    .notice-item {
      margin-bottom: 10rpx;
      text-align: justify;
    }
  }
}

.image-desc {
  margin-bottom: 20rpx;
  
  .desc-image {
    width: 100%;
    display: block;
  }
}

.product-desc {
  background: #FFFFFF;
  padding: 20rpx;

  .desc-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin: 20rpx 0 10rpx;
  }

  .desc-content {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
  }
}

.size-table {
  margin: 20rpx 0;
  border: 1rpx solid #EEEEEE;
  border-radius: 8rpx;
  overflow: hidden;

  .table-header, .table-row {
    display: flex;
    background: #F8F8F8;

    .cell {
      flex: 1;
      padding: 15rpx 10rpx;
      text-align: center;
      font-size: 24rpx;
      border-right: 1rpx solid #EEEEEE;
      border-bottom: 1rpx solid #EEEEEE;

      &:last-child {
        border-right: none;
      }
    }
  }

  .table-row {
    background: #FFFFFF;

    &:last-child {
      .cell {
        border-bottom: none;
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .submit-btn {
    width: 90%;
    height: 80rpx;
    line-height: 80rpx;
    background: #FF0000;
    color: #FFFFFF;
    font-size: 32rpx;
    border-radius: 40rpx;
    text-align: center;
    margin: 0;
    padding: 0;

    &::after {
      border: none;
    }
  }
}

.confirm-btn {
  position: fixed;
  right: 30rpx;
  bottom: 30rpx;
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #FF6B6B, #FF8E53);
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(255, 107, 107, 0.4);
  z-index: 1000;
  transition: all 0.3s;

  text {
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: 600;
  }

  &:active {
    transform: scale(0.9);
    box-shadow: 0 4rpx 15rpx rgba(255, 107, 107, 0.3);
  }
}
</style> 